package com.albert.View;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatImageButton;

public class GameButton extends AppCompatImageButton {

    private Handler handler = new Handler();
    private boolean isPressed = false;
    private int interval = 100; // 动作触发间隔，单位毫秒
    private OnRepeatListener repeatListener;

    public GameButton(Context context) {
        super(context);
        init();
    }

    public GameButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GameButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void init() {
        // 设置触摸监听器
        this.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isPressed = true;
                    setPressed(true);
                    startRepeating();
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    isPressed = false;
                    setPressed(false);
                    stopRepeating();
                    break;
            }
            return true; // 消费事件
        });
    }

    // 开始循环触发动作
    private void startRepeating() {
        handler.post(repeatRunnable);
    }

    // 停止循环
    private void stopRepeating() {
        handler.removeCallbacks(repeatRunnable);

        postDelayed(() -> { // 主要是为了安全起见
            repeatListener.onRepeat(false);
        }, 40);
        postDelayed(() -> { // 主要是为了安全起见
            repeatListener.onRepeat(false);
        }, 80);
    }

    // 循环执行的Runnable
    private final Runnable repeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (isPressed && repeatListener != null) {
                repeatListener.onRepeat(isPressed);
                handler.postDelayed(this, interval);
            }
        }
    };

    // 设置触发间隔
    public void setInterval(int interval) {
        this.interval = interval;
    }

    // 设置回调监听
    public void setOnRepeatListener(OnRepeatListener listener) {
        this.repeatListener = listener;
    }

    // 回调接口
    public interface OnRepeatListener {
        void onRepeat(Boolean isPressed);
    }
}
